/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package halali;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author martin100
 */
public class ShowMatcher {
    
        private final List<ShowTitle> shows;
        private final List<CSFDTitle> csfdTitles;
        private final int threadsCount;
        private final List<Thread> jobs;
        

        public ShowMatcher(List<ShowTitle> shows, int threadsCount,  List<CSFDTitle> csfdTitles) {
            Objects.requireNonNull(shows);
            Objects.requireNonNull(csfdTitles);
            if(shows.size() < 1 | csfdTitles.size() < 1){
                throw  new IllegalArgumentException("Insert some data please");
            }
            
            this.shows = shows;
            this.threadsCount = threadsCount;
            this.csfdTitles = csfdTitles;
            jobs = new ArrayList<>(threadsCount);
        }
        
        public void prepareJobs(){
            int batch = shows.size() / threadsCount;
            for (int i = 0; i < threadsCount; i++) {
                List<ShowTitle> tmp = shows.subList(i*batch, (i+1)*batch);
                jobs.add(new Thread(createBatch(new RelationSaverImpl(),String.valueOf(i),tmp,csfdTitles)));
            }
            
        }
        
        private Runnable createBatch(final RelationSaver rs, final String threadName, final List<ShowTitle> shows1, final List<CSFDTitle> csfdTitles1){
            return new Runnable() {
                
                private final List<ShowTitle> shows = shows1;
                private final List<CSFDTitle> csfdTitles = csfdTitles1;
                private String show;
                
                @Override
                public void run() {                
                    int count = 0;
                    System.out.println("Thread :"+threadName+" started!");
                    
                    
                    for (ShowTitle showTitle : shows) {
                        Integer findMatch = new TitleMatcher(csfdTitles, showTitle).findMatch();
                        if(findMatch != null){
                            rs.saveRelation(showTitle.showId, findMatch);
                        }
                        
                        
                        if(++count % 1000 == 0){
                            System.out.println("thread:"+threadName+" processed:"+count);
                        }
                    }
                    
                    System.out.println("JOB IS DONE!:"+threadName+" processed:"+count);
                }
            };
        }
        
        public void go(){
            for (Thread thread : jobs) {
                thread.start();
            }
        }
}
